using UnityEngine;
using System.Collections;

[System.Serializable]
public class PlaySoundOnWalk : MonoBehaviour {
	
	public AudioClip soundLeftFootForward;
	public AudioClip soundRightFootForward;
	
	public AudioClip soundLeftFootBackwards;
	public AudioClip soundRightFootBackwards;
	
	public AudioClip soundLeftFootSideStep;
	public AudioClip soundRightFootSideStep;
	
	public bool debug = false;
	
	public AudioSource source;
	
	//public float volume = 1f;
	
	float time = 0f;
	public float timeBetweenSteps = 0.7f;
	int sound = 0;
	bool playerWalking = false;
	
	string message = "Player outside!";
	
	private static int FORWARD = 0;
	private static int BACKWARD = 1;
	private static int LEFT = 2;
	private static int RIGHT = 3;

	// Use this for initialization
	void Start () {
		time = Time.time;
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey("w")) {
			playSound(FORWARD);
		} else if (Input.GetKey("s")) {
			playSound(BACKWARD);	
		} else if (Input.GetKey("a")) {
			playSound(LEFT);
		} else if (Input.GetKey("d")) {
			playSound(RIGHT);
		} else {
			playerWalking = false;	
		}
	}
	
	void OnTriggerEnter(Collider collision) {
		//message = collision.tag; 
		if (collision.tag == "Player") {
			message = "Player collided!";
			playerWalking = true;          
        }
	}
	
	void OnTriggerStay(Collider collision) {
		//message = collision.tag; 
		if (collision.tag == "Player") {
			message = "Player collided!";
			playerWalking = true;          
        }
	}
	
	void OnTriggerExit(Collider collisionInfo) {
        if (collisionInfo.tag == "Player") {			
			playerWalking = false;
			message = "Player outside!";
        }
    }
	
	public void playSound(int direction) {
		if (playerWalking) {
			if (!source.isPlaying && Time.time-time > timeBetweenSteps) {
				if (direction == FORWARD) {
					if (sound == 0) {
						source.PlayOneShot(soundLeftFootForward);
						sound++;
					}
					else {
						source.PlayOneShot(soundRightFootForward);
						sound = 0;
					}
				} else if (direction == BACKWARD) {
					if (sound == 0) {
						source.PlayOneShot(soundLeftFootBackwards);
						sound++;
					}
					else {
						source.PlayOneShot(soundRightFootBackwards);
						sound = 0;
					}
				} else if (direction == LEFT || direction == RIGHT) {
					if (sound == 0) {
						source.PlayOneShot(soundLeftFootSideStep);
						sound++;
					}
					else {
						source.PlayOneShot(soundRightFootSideStep);
						sound = 0;
					}
				}
				time = Time.time;
			}
		} else {
			source.Stop();	
		}
	}
	
	void OnGUI() {
		if (debug) {
			GUI.Box(new Rect(0, 400, 200, 100), message);	
		}
	}
}
